import base64
import pickle

from django.conf import settings
from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView
from random import randint
from django_redis import get_redis_connection
from rest_framework_jwt.views import ObtainJSONWebToken

from carts.utils import merge_cart_cookie_to_redis
from meiduo_mall.libs.yuntongxun.sms import CCP
from threading import Thread
from celery_tasks.sms_code.tasks import send_sms_code
from rest_framework.generics import ListAPIView, CreateAPIView, RetrieveAPIView, UpdateAPIView
from users.models import User
from users.serializers import UserSerializers, UserShowSerialiszers, UserEmailSerialiszers
from itsdangerous import TimedJSONWebSignatureSerializer as TJS


# def send_sms_code(mobile, sms_code):
#     ccp = CCP()
#     ccp.send_template_sms(mobile, [sms_code, '5'], 1)

# Create your views here.

# 判断用户名是否重复
class UserNameView(APIView):
    def get(self, request, username):
        # 获取前端数据
        count = User.objects.filter(username=username).count()
        return Response(
            {'count': count}
        )


class MobileView(APIView):
    def get(self, request, mobile):
        count = User.objects.filter(mobile=mobile).count()
        return Response(
            {'count': count}
        )


class SMS_Code_View(APIView):
    # APIView 不提供  分页 排序方法
    def get(self, request, mobile):
        # 获取前端手机号
        # 验证手机号
        # 判断 前段请求是否在60秒内
        conn = get_redis_connection('sms_code')
        flag = conn.get('sms_code_flag_%s' % mobile)
        if flag:
            return Response({'error': '请求过于频繁'}, status=403)

        sms_code = '%06d' % randint(0, 999999)
        print(sms_code)
        # 创建管道
        pl = conn.pipeline()

        # 保存短信  redis
        # 读取数据

        # 写入数据
        pl.setex('sms_code_%s' % mobile, 300, sms_code)

        # 写入一个标志位
        pl.setex('sms_code_flag_%s' % mobile, 60, 2)
        # 将指令通过管道链接
        pl.execute()

        # 利用线程解决等待
        # t = Thread(target=send_sms_code, kwargs={'mobile':mobile, 'sms_code':sms_code})
        # t.start()

        # 使用celery

        send_sms_code.delay(mobile, sms_code)
        return Response('ok')


class UserView(CreateAPIView):
    # def post(self,request,):
    serializer_class = UserSerializers


class UserShowView(RetrieveAPIView):
    serializer_class = UserShowSerialiszers

    queryset = User.objects.all()

    # 重写get_object方法  获取token值
    def get_object(self):
        return self.request.user


# 获取更新邮箱
class UserEmailView(UpdateAPIView):
    serializer_class = UserEmailSerialiszers

    # 重写get_oject
    def get_object(self):
        return self.request.user


class UserEmailVifyView(APIView):
    def get(self, request):
        # 获取前端数据
        token = request.query_params.get('token')
        tjs = TJS(settings.SECRET_KEY, 300)
        try:
            data = tjs.loads(token)
        except:
            return Response({'error': '错误的token'}, status=400)

        username = data.get('username')
        user = User.objects.get(username=username)

        user.email_active = True
        user.save()
        return Response({'email_active': user.email_active})


# 重写登录方法  合并购物车   cookie合并到redis内
class UserLoginView(ObtainJSONWebToken):
    def post(self, request, *args, **kwargs):
        # 不修改原有登录逻辑
        response = super().post(request, *args, **kwargs)
        # 增加合并购物车
        serializer = self.get_serializer(data=request.data)

        if serializer.is_valid():
            # 获取user
            user = serializer.object.get('user') or request.user
            response = merge_cart_cookie_to_redis(request, response, user)
            return response
        return response
